/**
 * @projectName interview_-assistant
 * @package org.example.util
 * @className org.example.util.ContentParser
 * @copyright Copyright 2025 Thunisoft, Inc All rights reserved.
 */
package org.example.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Component
@Slf4j
public class PdfConverter {
    
    /**
     * 将PDF文件转换为TXT文件
     * @param pdfPath PDF文件路径
     * @param txtPath 输出TXT文件路径
     * @return 转换结果
     */
    public boolean convertPdfToTxt(String pdfPath, String txtPath) {
        try (PDDocument document = PDDocument.load(new File(pdfPath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(txtPath))) {
            
            // 创建PDF文本提取器
            PDFTextStripper stripper = new PDFTextStripper();
            
            // 设置按顺序读取
            stripper.setSortByPosition(true);
            
            // 提取文本
            String text = stripper.getText(document);
            
            // 写入TXT文件
            writer.write(text);
            
            log.info("PDF转换TXT成功: {} -> {}", pdfPath, txtPath);
            return true;
            
        } catch (IOException e) {
            log.error("PDF转换TXT失败: " + e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 将PDF文件转换为TXT文本（返回字符串）
     * @param pdfPath PDF文件路径
     * @return 转换后的文本内容
     */
    public String convertPdfToText(String pdfPath) throws IOException {
        try (PDDocument document = PDDocument.load(new File(pdfPath))) {
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(true);
            return stripper.getText(document);
        }
    }
    
    /**
     * 将PDF文件转换为TXT文本（支持字节数组输入）
     * @param pdfBytes PDF文件的字节数组
     * @return 转换后的文本内容
     */
    public String convertPdfBytesToText(byte[] pdfBytes) throws IOException {
        try (PDDocument document = PDDocument.load(new ByteArrayInputStream(pdfBytes))) {
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(true);
            return stripper.getText(document);
        }
    }
}